package common;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.hdfs.DistributedFileSystem;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Vector;


/**
 * Created by yeyulong on 2017/4/7.
 */
public class HDFSOperator {
    private static Configuration conf = new Configuration();
    private static FileSystem fileSystem = null;

    static {
        try {
            fileSystem = FileSystem.get(new URI("hdfs://dw2:8020"),conf);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }

        if(fileSystem instanceof DistributedFileSystem) {
            // System.out.println("HDFS is the underlying filesystem");
            ;
        }
        else {
            System.out.println("Other type of file system " + fileSystem.getClass());
            fileSystem = null;
        }
    }

    public static boolean exists(String spath) {
        boolean ret;

        try {
            ret = fileSystem.exists(new Path(spath));
        } catch (IOException e) {
            e.printStackTrace();
            ret = false;
        }

        return ret;
    }

    public static Vector<String> ls(String spath) {
        Vector<String> r_vec = new Vector<String>();
        FileStatus[] fileStatuses = null;
        try {
            fileStatuses = fileSystem.listStatus(new Path(spath));
        } catch (FileNotFoundException e) {
            // e.printStackTrace();
        } catch (IOException e) {
            // e.printStackTrace();
        }

        if (fileStatuses != null) {
            for (FileStatus filestatus: fileStatuses) {
                r_vec.add(filestatus.getPath().toString());
            }
        }

        return r_vec;
    }


    public static boolean mkdirs(String spath) {
        boolean ret;
        try {
            ret = fileSystem.mkdirs(new Path(spath));
        } catch (IOException e) {
            e.printStackTrace();
            ret = false;
        }

        return ret;
    }

    /*
        删除文件
     */
    public static boolean delete(String spath) {
        boolean ret = true;
        try {
            ret = fileSystem.delete(new Path(spath), true);
        } catch (IOException e) {
            e.printStackTrace();
            ret = false;
        }

        return ret;
    }
}
